from re import I
from django.shortcuts import render,HttpResponse,redirect
from django.http import JsonResponse
from django.views.decorators import csrf
from web import models
from web.forms.files import FolderModelForm, FileModelForm
from django.views.decorators.csrf import csrf_exempt

from utils.tencent.cos import delete_cos_file, delete_cos_files
from utils.tencent.cos import get_credential_dict
import json
def files(request,project_id):
    if request.method == "GET":
        # 从数据库读取文件列表，并显示
        folder_obj = FolderModelForm(request,None)
        folder_id = request.GET.get('folder_id','')
        folder_list = []
        parent_obj = None
        if not folder_id.isdecimal():
            # folder_list = []
            # 根目录
            forms = models.FileRepository.objects.filter(project_id = project_id,parent__isnull=True).order_by('-file_type')
        else:
            # 获取导航条
            obj = models.FileRepository.objects.filter(id=int(folder_id), project_id=project_id,
                                                       file_type=2).first()
            while obj:
                folder_list.insert(0,obj)
                obj = obj.parent
                
            forms = models.FileRepository.objects.filter(project_id = project_id,parent_id=folder_id).order_by('-file_type')
            parent_obj = models.FileRepository.objects.filter(id = folder_id, project_id=project_id).first()
        
        context = {'forms':forms,
                   'folder_list':folder_list,
                   'folder_obj':folder_obj,
                   'folder_id':folder_id}
        return render(request, 'web/files.html',context) 
    else:
        ret = {'status': True, 'msg':''}
        folder_id = request.GET.get('folder_id','')
        parent_obj = None
        if folder_id.isdecimal():
            parent_obj = models.FileRepository.objects.filter(id=int(folder_id),
                            file_type=2,project_id=project_id).first()
        folder_obj = FolderModelForm(request,parent_obj, data=request.POST)
        
        fid = request.POST.get('fid','')
        edit_obj = None
        if fid.isdecimal():
            # 编辑
            edit_obj = models.FileRepository.objects.filter(id=fid,project_id=project_id,file_type=2).first()
        else:
            # 新建
            pass
        
        if edit_obj:
            folder_obj = FolderModelForm(request,parent_obj, data=request.POST,instance=edit_obj)
        else:
            # 新建
            folder_obj = FolderModelForm(request,parent_obj, data=request.POST)
        
        
        if folder_obj.is_valid():
            
            folder_obj.instance.file_type=2
            folder_obj.instance.project_id = project_id
            folder_obj.instance.parent = parent_obj
            folder_obj.instance.update_user = request.tracer.user
            folder_obj.save() 
            return JsonResponse(ret)
        else:
            ret['status'] = False
            ret['msg'] = folder_obj.errors
            return JsonResponse(ret)

            
def files_delete(request, project_id):
    if request.method == "GET":
        fid = request.GET.get('fid')

    if fid.isdecimal():
        delete_obj = models.FileRepository.objects.filter(id=fid,project_id=project_id).first()
    else:
        delete_obj=None 
     
    if delete_obj:
        if delete_obj.file_type == 1:
            # 删除文件：删除cos，删除数据库，空间归还
            response = delete_cos_file(request.tracer.project.bucket,
                                        request.tracer.project.region,
                                        delete_obj.key 
                                       )
            request.tracer.project.used_space -= delete_obj.file_size
            request.tracer.project.save()
            delete_obj.delete()
            # print('files.py/file_delete/response:',response)
        else:
            # 删除文件夹: 删除文件夹下所有文件(删除cos, 删除数据库，空间归还)
            total_size = 0
            folder_list = [delete_obj,]
            key_list = []
            for folder in folder_list:
                objs = folder.child.all()
                for del_obj in objs:
                    if del_obj.file_type==2:
                        #是文件夹添加到folder_list 
                        folder_list.append(del_obj)
                    else:
                        #删除文件
                        key_list.append({'Key': del_obj.key})
                        total_size += del_obj.file_size
                        del_obj.delete() # TODO.有问题，应先删cos，然后根据response删数据库
            # 删除根目录，其余目录由数据库级联删除
            request.tracer.project.used_space -= total_size 
            request.tracer.project.save()
            delete_obj.delete()
             
            response = delete_cos_files(
                    request.tracer.project.bucket,
                    request.tracer.project.region,
                    key_list
            )
            # print('files.py/file_delete/response:',response)
            
    else:
        # 没有找到可以删除的内容
        pass
    return JsonResponse({'status':True})

def cos_credential(request,project_id):
    bucket = request.GET.get('bucket')
    region = request.GET.get('region')
    # bucket = "xiao-1253629186"
    # region = 'ap-beijing'
    result_dict = get_credential_dict(bucket,region)
    # print('files/cos_credential:',result_dict)
    return JsonResponse(result_dict)

@csrf_exempt
def files_size_auth(request, project_id):
    ret = {'status': True, 'msg':''}
    files_info = json.loads(request.body.decode('utf-8'))  #把字节decode成字符串，然后通过json转换成字典
    # print(files_info)
    max_single_file_size = request.tracer.price_policy.per_file_size * 1024 *1024
    max_total_file_size = request.tracer.price_policy.project_space *1024 * 1024 *1024
    total_upload_size = 0
    for file in files_info:
        if file['size'] > max_single_file_size:
            ret['status'] = False
            ret['msg'] = "单个文件(%s)超过范围，建议升级套餐"%file['name']
            return JsonResponse(ret)
        total_upload_size += file['size']
    if total_upload_size > max_total_file_size - request.tracer.project.used_space:
        ret['status'] = False
        ret['msg'] = "上传文件超过项目允许范围，建议升级套餐"
        return JsonResponse(ret)
        
    return JsonResponse(ret)

# @csrf_exempt
def files_upload(request, project_id):
    if request.method == "GET":
        return JsonResponse({})      
    else:
        ret = {'status':True, 'msg':''}
        forms = FileModelForm(request, data=request.POST)
        if forms.is_valid():
            data = forms.cleaned_data
            
            data.pop("etag")
            data.update({'file_type':1, 
                         'project':request.tracer.project,
                         'update_user': request.tracer.user,
                         })
            instance = models.FileRepository.objects.create(**data)
           
            #更新used_space
            request.tracer.project.used_space += instance.file_size
            request.tracer.project.save()
            
            #发送显示数据到前端
            ret['msg']={
                'id': instance.id,
                'name':instance.name,
                'file_size': instance.file_size,
                'update_user': instance.update_user.username,
                'update_datetime':instance.update_datetime.strftime("%Y{y}%m{m}%d{d} %H:%M").format(y='年',m='月',d='日'),
                'key': instance.key,
                # 'file_path':instance.file_path,
            }
             
        else:
            ret['status'] = False
            msg = "文件验证异常"
            for key, value in forms.errors.items():
                msg = value[0]
                break
            ret['msg'] = msg 
    
        return JsonResponse(ret)      

def file_download(request, project_id):
    folder_id = request.GET.get('folder_id','')
    data = None
    if folder_id.isdecimal():
        file_obj = models.FileRepository.objects.filter(project_id=project_id, 
                                    update_user=request.tracer.user,
                                    id = folder_id,
                                    file_type=1).first()
        if file_obj:
        
            import requests
            res = requests.get(file_obj.file_path)

            # 文件分块处理（适用于大文件）     @孙歆尧
            data = res.iter_content()
            
            # 设置content_type=application/octet-stream 用于提示下载框        @孙歆尧
            response = HttpResponse(data, content_type="application/octet-stream")
            from django.utils.encoding import escape_uri_path

            # 设置响应头：中文件文件名转义      @王洋
            response['Content-Disposition'] = "attachment; filename={};".format(escape_uri_path(file_obj.key))
            return response
    
    data=None
    response = HttpResponse(data)
    from django.utils.encoding import escape_uri_path
    response['Content-Disposition'] = "attachment; filename={};".format(escape_uri_path('文件下载异常'))
    return response